package com.sk.weichat.ui.mucfile;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;

import com.sk.weichat.bean.EmptyData;
import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.adapter.DividerAdapter;
import com.sk.weichat.ui.mucfile.adapter.EmptyAdapter;
import com.sk.weichat.ui.mucfile.adapter.FileAdapter;
import com.sk.weichat.ui.mucfile.adapter.TypeAdapter;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.util.MediaHelper;
import com.umeng.commonsdk.debug.E;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.Action_Click;
import static com.sk.weichat.ui.mucfile.bean.FileBean.APK;
import static com.sk.weichat.ui.mucfile.bean.FileBean.DIR;


public class MediaApkFragment2 extends LazyFragment implements MediaHelper.OnQueryListener {
    SmartRefreshLayout refreshLayout;

    EmptyData emptyData = new EmptyData("该分类暂无内容");

    //记录展开的项
    Map<String, Boolean> expandMap = new HashMap<>();
    //记录选择的Item
    Map<String, Boolean> checkedMap = new HashMap<>();

    //缓存 key 为文件目录
    Map<String, List<FileBean>> typeBeans = new HashMap<>();

    private DelegateAdapter delegateAdapter;

    private LinkedList<DelegateAdapter.Adapter> adapterList = new LinkedList<>();

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_media_apk;
    }

    @Override
    protected void loadData() {
        //扫描文件时间过长，缓存不为空，显示缓存
        List<File> files = MediaHelper.getInstance().getFilesQueryCache();
        if (files != null) {
            onDataSuccess(files);
        } else {
            refreshLayout.autoRefresh();
        }
    }

    @Override
    protected void initView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                realLoadData();
            }
        });

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);

    }


    private void selectItem(FileBean fileBean) {
        if (AddMucFileActivity2.isAllowToSelect() || fileBean.isChecked()) {
            fileBean.setChecked(!fileBean.isChecked());
            checkedMap.put(fileBean.getFile().getAbsolutePath(), fileBean.isChecked());

            //发送广播
            Intent intent = new Intent();
            intent.setAction(Action_Click);
            intent.putExtra(FileBean.FileBean_Key, fileBean);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.select_file_count_place_holder, 9), Toast.LENGTH_SHORT).show();
        }
    }

    private void realLoadData() {
        //查询
        MediaHelper.getInstance().getMediaFiles(getActivity().getContentResolver(), this);
    }

    private void onDataSuccess(List<File> files) {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                //耗时操作
                try {
                    adapterList.clear();
                    typeBeans.clear();
                    if (files.size() > 0) {
                        fillData(files);
                    } else {
                        adapterList.add(new EmptyAdapter(mContext));
                    }
                } catch (Exception e) {
                    emitter.onError(e);
                }
                emitter.onNext(new Object());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        delegateAdapter.clear();
                        delegateAdapter.setAdapters(adapterList);
                        delegateAdapter.notifyDataSetChanged();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    boolean once = false; //首次加载展开第一项

    private void fillData(List<File> files) {
        //

        Map<String, TypeAdapter> typeAdapterMap = new HashMap<>();

        for (int i = 0; i < files.size(); i++) {
            try {
                File file = files.get(i);
                String suffix = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1, file.getAbsolutePath().length());
                if (suffix.equalsIgnoreCase("apk") && file.length() > 1024) {
                    String parent = file.getParent();
                    if (typeAdapterMap.get(parent) == null) {
                        //
                        List<FileBean> fileBeans = new ArrayList<>();
                        FileBean fileBean = new FileBean();
                        fileBean.setType(DIR);
                        fileBean.setTypeName(parent);
                        fileBean.setExpand(expandMap.get(parent) != null ? expandMap.get(parent) : false);
                        if (!once) {
                            once = true;
                            fileBean.setExpand(true);
                            expandMap.put(parent, true);
                        }
                        fileBeans.add(fileBean);
                        TypeAdapter typeAdapter = new TypeAdapter(mContext, fileBeans);
                        typeAdapter.setOnTypeClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                FileBean tbean = typeAdapter.getData().get(0);
                                if (tbean.isExpand()) {
                                    //折叠
                                    tbean.setExpand(false);
                                    expandMap.put(parent, false);
                                    int index = adapterList.indexOf(typeAdapter) + 1;
                                    if (adapterList.get(index) instanceof FileAdapter) {
                                        FileAdapter fileAdapter = (FileAdapter) adapterList.get(index);
                                        int size = fileAdapter.getData().size();
                                        fileAdapter.getData().clear();
                                        fileAdapter.notifyItemRangeRemoved(0, size);
                                    }
                                } else {
                                    //展开
                                    tbean.setExpand(true);
                                    expandMap.put(parent, true);
                                    int index = adapterList.indexOf(typeAdapter) + 1;
                                    if (adapterList.get(index) instanceof FileAdapter) {
                                        FileAdapter fileAdapter = (FileAdapter) adapterList.get(index);
                                        List<FileBean> fileBeans1 = typeBeans.get(tbean.getTypeName());
                                        fileAdapter.getData().addAll(fileBeans1);
                                        fileAdapter.notifyItemRangeInserted(0, fileBeans1.size());
                                    }
                                }
                                typeAdapter.notifyItemChanged(0);
                            }
                        });
                        adapterList.add(typeAdapter);
                        typeAdapterMap.put(parent, typeAdapter);
                        FileAdapter fileAdapter = new FileAdapter(mContext, new ArrayList<>());
                        fileAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
                            @Override
                            public void onClick(FileBean fileBean, int pos) {
                                selectItem(fileBean);
                                fileAdapter.notifyItemChanged(pos);
                            }
                        });
                        FileBean fileBean1 = new FileBean();
                        fileBean1.setFileName(file.getName());
                        fileBean1.setFile(file);
                        fileBean1.setType(APK);
                        fileBean1.setChecked(checkedMap.get(file.getAbsolutePath()) == null ? false : checkedMap.get(file.getAbsolutePath()));
                        if (fileBean.isExpand()) {
                            fileAdapter.getData().add(fileBean1);
                        }
                        List<FileBean> cache = new ArrayList<>();
                        cache.add(fileBean1);
                        typeBeans.put(parent, cache);
                        adapterList.add(fileAdapter);
                        adapterList.add(new DividerAdapter(mContext));
                    } else {
                        DelegateAdapter.Adapter adapter = typeAdapterMap.get(parent);
                        int index = adapterList.indexOf(adapter) + 1;
                        FileBean fileBean1 = new FileBean();
                        fileBean1.setFile(file);
                        fileBean1.setType(APK);
                        fileBean1.setFileName(file.getName());
                        fileBean1.setChecked(checkedMap.get(file.getAbsolutePath()) == null ? false : checkedMap.get(file.getAbsolutePath()));
                        typeBeans.get(((TypeAdapter) adapter).getData().get(0).getTypeName()).add(fileBean1);
                        DelegateAdapter.Adapter adapter1 = adapterList.get(index);
                        if (adapter1 instanceof FileAdapter) {
                            if (((TypeAdapter) adapter).getData().get(0).isExpand()) {
                                FileAdapter fileAdapter = (FileAdapter) adapter1;
                                fileAdapter.getData().add(fileBean1);
                            }
                        }

                    }
                }
            } catch (Exception e) {
            }

        }

    }

    @Override
    public void onSuccess(List<File> files) {
        refreshLayout.finishRefresh();
        onDataSuccess(files);
    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.finishRefresh();
    }
}
